<template>
  <div class="p-3">
    <a-card style="height: 820px" :bordered="false">
      <div class="mb-4 flex items-center justify-between">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="修改时间">
            <a-range-picker v-model:value="searchForm.time" />
          </a-form-item>
          <a-form-item label="所属项目">
            <a-tree-select
              v-model:value="searchForm.comId"
              tree-node-filter-prop="label"
              style="width: 260px"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="comanyList"
              placeholder="请选择所属项目"
            />
          </a-form-item>
          <a-form-item label="修改人">
            <a-tree-select
              v-model:value="searchForm.operator"
              tree-data-simple-mode
              allow-clear
              style="width: 150px"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="selectList"
              placeholder="请选择操作人"
              :load-data="onLoadData"
            />
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              class="mr-3"
              :icon="h(SearchOutlined)"
              @click="onSearch"
              >查询</a-button
            >
          </a-form-item>
        </a-form>
        <a-button type="primary" @click="showModal"> 新增 </a-button>
      </div>
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        class="mt-3"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex == 'paymentType'">
            <template v-if="record.paymentType == 1">
              供暖
            </template>
            <template v-if="record.paymentType == 2">
              制冷
            </template>
            <template v-if="record.paymentType == 3">
              供水
            </template>
            <template v-if="record.paymentType == 4">
              光伏供电
            </template>
          </template>
          <template v-if="column.dataIndex == 'action'">
            <a-button type="link" @click="handleEdit(record)">编辑</a-button>
            <a-popconfirm
              placement="bottom"
              ok-text="是"
              cancel-text="否"
              title="确认删除吗？"
              @confirm="handleDelete(record)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>
    <!-- 参数弹窗 -->
    <a-modal
      :visible="modalVisible"
      :title="isEdit ? '编辑参数' : '新增参数'"
      width="1600px"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form
        :model="formData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        ref="formRef"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="归属机构" name="comId">
              <a-tree-select
                v-model:value="formData.comId"
                tree-node-filter-prop="label"
                style="width: 260px"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="comanyList"
                placeholder="请选择所属项目"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="缴费类型">
              <a-radio-group
                v-model:value="formData.paymentType"
                name="radioGroup"
              >
                <a-radio :value="1">供暖</a-radio>
                <a-radio :value="2">制冷</a-radio>
                <a-radio :value="3">供水</a-radio>
                <a-radio :value="4">光伏供电</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="证明材料与缴费关联" name="materialFees">
              <a-switch
                v-model:checked="formData.materialFees"
                :checkedValue="0"
                :unCheckedValue="1"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="居民是否免税" name="taxExemption">
              <a-switch
                v-model:checked="formData.taxExemption"
                :checkedValue="0"
                :unCheckedValue="1"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="线下缴费" name="offlinePayment">
              <a-switch
                v-model:checked="formData.offlinePayment"
                :checkedValue="0"
                :unCheckedValue="1"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="线上缴费" name="onlinePayment">
              <a-switch
                v-model:checked="formData.onlinePayment"
                :checkedValue="0"
                :unCheckedValue="1"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="本年度线上缴费" name="onlinePaymentYear">
              <a-switch
                v-model:checked="formData.onlinePaymentYear"
                :checkedValue="0"
                :unCheckedValue="1"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="停供自动生成应收" name="autoReceivable">
              <a-switch
                v-model:checked="formData.autoReceivable"
                :checkedValue="0"
                :unCheckedValue="1"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="线上停供审批" name="onlineApproval">
              <a-switch
                v-model:checked="formData.onlineApproval"
                :checkedValue="0"
                :unCheckedValue="1"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="收费期" name="tolFeriod">
              <a-radio-group v-model:value="formData.tolFeriod">
                <a-radio :value="0">上期</a-radio>
                <a-radio :value="1">下一期</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item
          label="收据开头字母"
          :label-col="{ span: 3 }"
          :wrapper-col="{ span: 21 }"
          name="letter"
        >
          <a-input
            v-model:value="formData.letter"
            placeholder="收据开头字母不超过3个字符，只能是英文字母"
          />
        </a-form-item>

        <a-form-item
          label="报停申请注意事项"
          :label-col="{ span: 3 }"
          :wrapper-col="{ span: 21 }"
          name="submittedPrecautions"
        >
          <div class="editor-container">
            <UEditor
              v-model="formData.submittedPrecautions"
              :height="300"
              width="100%"
              placeholder="请输入报停申请注意事项"
            />
          </div>
        </a-form-item>

        <a-form-item
          label="恢复申请注意事项"
          :label-col="{ span: 3 }"
          :wrapper-col="{ span: 21 }"
          name="applyForPrecautions"
        >
          <div class="editor-container">
            <UEditor
              v-model="formData.applyForPrecautions"
              :height="300"
              width="100%"
              placeholder="请输入恢复申请注意事项"
            />
          </div>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, h } from 'vue';
import {
  getParameterMaintenanceInfo,
  addParameterMaintenanceInfo,
  editParameterMaintenanceInfo,
  delParameterMaintenanceInfo,
} from '#/api/core/setting';
import { getOperatorApi } from '#/api/core/statistical';
import { getCompanyTree } from '#/api/core/develop';
import { SearchOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import UEditor from '#/components/Editor/UEditor.vue';
import dayjs from 'dayjs';

interface SearchFormData {
  comId: string | number | null;
  time: any; // 使用any是因为a-range-picker的值类型比较复杂
  operator: string | number | null;
}

const searchForm = reactive<SearchFormData>({
  comId: '',
  time: '',
  operator: '',
});
interface TreeNode {
  id: string | number;
  value: string | number;
  title: string;
  key: string | number;
  isLeaf: boolean;
  children?: TreeNode[];
}

const formRef = ref();
const selectList = ref<TreeNode[]>([]);
const getList = () => {
  getOperatorApi(null)
    .then((res: any) => {
      // console.log(res);
      selectList.value = (res || []).map((item: any) => {
        return {
          id: item.id,
          value: item.id,
          title: item.name,
          key: item.id,
          isLeaf: !!item.userId, // 如果有userId说明是叶子节点
        };
      });
    })
    .catch((error) => {
      console.error('获取操作人员列表失败:', error);
      message.error('获取操作人员列表失败');
    });
};
getList();
const onLoadData = (treeNode: any) => {
  return new Promise((resolve) => {
    // console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getOperatorApi(treeNode.id)
      .then((res: any) => {
        const children = res.map((item: any) => {
          // console.log(item);
          return {
            id: item.userId ? item.userId : item.id,
            value: item.name ? item.name : item.name,
            title: item.name,
            key: item.userId ? item.userId : item.id,
            isLeaf: !!item.userId, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          for (let node of nodes) {
            if (node.key === treeNode.id) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(selectList.value);
        selectList.value = [...selectList.value];
        // console.log(selectList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error('加载子节点失败:', error);
        message.error('加载子节点失败');
        resolve(undefined);
      });
  });
};
onMounted(() => {
  getTableData();
});
interface CompanyTreeNode {
  key: string | number;
  label: string;
  value: string | number;
  isLeaf: boolean;
  children: CompanyTreeNode[];
}

const comanyList = ref<CompanyTreeNode[]>([]);
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): any[] => {
      // console.log(tree)
      return tree.map((item: any) => {
        const processedItem = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData || [];
    // console.log(comanyList.value);
  });
};
// 弹窗显示状态
const modalVisible = ref<boolean>(false);
const isEdit = ref<boolean>(false);
const currentEditId = ref<string | number>('');

// 表单数据
interface FormData {
  comId: number;
  organization: string;
  paymentType: number;
  // feeProject: string;
  findParameter: number;
  materialAssociation: number;
  taxExemption: number;
  offlinePayment: number;
  onlinePayment: number;
  currentYearOnlinePayment: number;
  autoGenerateReceivable: number;
  onlineStopApproval: number;
  mobileBilling: number;
  receiptPrefix: string;
  stopNotice: string;
  restoreNotice: string;
  fontFamily: string;
  fontFamily2: string;
}

const formData = reactive<FormData>({
  comId: '',
  comName: '',
  materialFees: 1,
  paymentType:1,
  letter: 1,
  electronicSeal: 1,
  onlinePayment: 1,
  heating: 1,
  refrigeration: 1,
  water: 1,
  supply: 1,
  tolFeriod: 1,
  offlinePayment: 1,
  onlinePaymentYear: 1,
  autoReceivable: 1,
  onlineApproval: 1,
  heatingYear: '',
  submittedPrecautions: '',
  applyForPrecautions: '',
});

// 表格数据
interface TableData {
  id?: string | number;
  comName?: string;
  materialFees?: number;
  paymentType?: number;
  letter?: string;
  electronicSeal?: number;
  onlinePayment?: number | string;
  heating?: number;
  refrigeration?: number;
  water?: number;
  supply?: number;
  tolFeriod?: number | string;
  offlinePayment?: number;
  onlinePaymentYear?: number;
  autoReceivable?: number;
  onlineApproval?: number;
  heatingYear?: string;
  submittedPrecautions?: string;
  applyForPrecautions?: string;
  operator?: string;
  dateTime?: string;
  // feeProject?: string;
  taxExemption?: number;
  [key: string]: any;
}

const dataSource = ref<TableData[]>([]);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const onSearch = () => {
  interface QueryParams {
    pageNo: number;
    pageSize: number;
    comId: string | number;
    time: string;
    operator: string | number;
  }

  const query: QueryParams = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    comId: searchForm.comId ?? '',
    time: searchForm.time
      ? dayjs(searchForm.time[0]).format('YYYY-MM-DD') +
        ',' +
        dayjs(searchForm.time[1]).format('YYYY-MM-DD')
      : '',
    operator: searchForm.operator ?? '',
  };

  console.log('查询参数:', query);

  // 由于不需要实际对接接口，这里模拟数据
  // 实际项目中，这里应该调用API
  getParameterMaintenanceInfo(query).then((res: any) => {
    console.log(res);
    dataSource.value = res.data.data.data;
    pagination.total = res.data.data.total;
  });
};
// 显示弹窗
const showModal = () => {
  isEdit.value = false;
  currentEditId.value = '';
  modalVisible.value = true;
};

// 确认提交
const handleOk = () => {
  if (isEdit.value) {
    // 编辑现有数据
    // console.log('编辑数据:', editData);
    editParameterMaintenanceInfo(formData).then((res: any) => {
      // console.log(res);
      if (res.data.code == 200) {
        message.success('编辑成功');
        // 关闭弹窗
        modalVisible.value = false;
        onSearch();
      } else {
        message.error('添加失败');
      }
      // message.success('编辑成功');
    });
    // 更新dataSource中的数据
    // const index = dataSource.value.findIndex(
    //   (item) => item.id === currentEditId.value,
    // );
    // if (index !== -1) {
    //   dataSource.value[index] = editData;
    // }
  } else {
    console.log(formData);
    // 新增数据
    addParameterMaintenanceInfo(formData).then((res: any) => {
      // console.log(res);
      if (res.data.code == 200) {
        message.success('添加成功');
        // 关闭弹窗
        modalVisible.value = false;
        onSearch();
      } else {
        message.error('添加失败');
      }
    });
    // 添加到dataSource
    // dataSource.value.unshift(newData);
  }

  // // 更新分页总数
  // pagination.total = dataSource.value.length;
};

// 取消
const handleCancel = () => {
  modalVisible.value = false;
  isEdit.value = false;
  currentEditId.value = '';
  // 重置表单数据
  formRef.value.resetFields();
  // Object.assign(formData, {
  //   organization: '',
  //   // feeProject: '',
  //   findParameter: false,
  //   materialAssociation: false,
  //   taxExemption: false,
  //   offlinePayment: false,
  //   onlinePayment: '微信',
  //   currentYearOnlinePayment: false,
  //   autoGenerateReceivable: false,
  //   onlineStopApproval: false,
  //   mobileBilling: '上期',
  //   receiptPrefix: '',
  //   stopNotice: '',
  //   restoreNotice: '',
  //   fontFamily: 'Normal',
  //   fontFamily2: 'Normal',
  // });
};

const columns = [
  {
    title: '归属机构',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
  },
  {
    title: '证明材料与缴费关联',
    dataIndex: 'materialFees',
    key: 'materialFees',
    align: 'center',
  },
  {
    title: '收据开头字母',
    dataIndex: 'letter',
    key: 'letter',
    align: 'center',
  },
  {
    title: '收据电子章',
    dataIndex: 'electronicSeal',
    key: 'electronicSeal',
    align: 'center',
  },
  {
    title: '线上缴费',
    dataIndex: 'onlinePayment',
    key: 'onlinePayment',
    align: 'center',
  },
  {
    title: '缴费类型',
    dataIndex: 'paymentType',
    key: 'paymentType',
    align: 'center',
  },
  // {
  //   title: '供暖',
  //   dataIndex: 'heating',
  //   key: 'heating',
  //   align: 'center',
  // },
  // {
  //   title: '制冷',
  //   dataIndex: 'refrigeration',
  //   key: 'refrigeration',
  //   align: 'center',
  // },
  // {
  //   title: '供水',
  //   dataIndex: 'water',
  //   key: 'water',
  //   align: 'center',
  // },
  // {
  //   title: '光伏供电',
  //   dataIndex: 'supply',
  //   key: 'supply',
  //   align: 'center',
  // },
  {
    title: '线下缴费',
    dataIndex: 'offlinePayment',
    key: 'offlinePayment',
    align: 'center',
  },
  {
    title: '本年度线上缴费',
    dataIndex: 'onlinePaymentYear',
    key: 'onlinePaymentYear',
    align: 'center',
  },
  {
    title: '停供自动生成应收',
    dataIndex: 'autoReceivable',
    key: 'autoReceivable',
    align: 'center',
  },
  {
    title: '线上停供审批',
    dataIndex: 'onlineApproval',
    key: 'onlineApproval',
    align: 'center',
  },
  {
    title: '收费期',
    dataIndex: 'tolFeriod',
    key: 'tolFeriod',
    align: 'center',
  },
  {
    title: '恢复供热年度',
    dataIndex: 'heatingYear',
    key: 'heatingYear',
    align: 'center',
  },
  {
    title: '报停申请注意事项',
    dataIndex: 'submittedPrecautions',
    key: 'submittedPrecautions',
    align: 'center',
  },
  {
    title: '恢复申请注意事项',
    dataIndex: 'applyForPrecautions',
    key: 'applyForPrecautions',
    align: 'center',
  },
  {
    title: '修改人',
    dataIndex: 'operator',
    key: 'operator',
    align: 'center',
  },
  {
    title: '修改时间',
    dataIndex: 'dateTime',
    key: 'dateTime',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'center',
    width: 180,
    fixed: 'right',
  },
];

// 编辑处理函数
const handleEdit = (record: TableData) => {
  isEdit.value = true;
  currentEditId.value = record.id || '';
  modalVisible.value = true;

  // 填充表单数据
  Object.assign(formData, {
    id: record.id,
    comId: record.comId,
    materialFees: record.materialFees,
    paymentType: record.paymentType,
    letter: record.letter,
    electronicSeal: record.electronicSeal,
    onlinePayment: record.onlinePayment,
    heating: record.heating,
    refrigeration: record.refrigeration,
    water: record.water,
    supply: record.supply,
    offlinePayment: record.offlinePayment,
    onlinePaymentYear: record.onlinePaymentYear,
    autoReceivable: record.autoReceivable,
    onlineApproval: record.onlineApproval,
    tolFeriod: record.tolFeriod,
    heatingYear: record.heatingYear,
    submittedPrecautions: record.submittedPrecautions,
    applyForPrecautions: record.applyForPrecautions,
  });
};
const handleDelete = (e: any) => {
  delParameterMaintenanceInfo(e.id).then((res: any) => {
    console.log(res);
    if (res.data.code == 200) {
      message.success('删除成功');
      onSearch();
    } else {
      message.error('删除失败');
    }
  });
};
</script>
<style scoped>
.editor-container {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
}

.editor-toolbar {
  padding: 8px 12px;
  border-bottom: 1px solid #d9d9d9;
  background-color: #fafafa;
  display: flex;
  align-items: center;
  gap: 4px;
  border-top-left-radius: 6px;
  border-top-right-radius: 6px;
}

.editor-toolbar .ant-btn {
  padding: 0 6px;
  height: 24px;
  min-width: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.editor-toolbar .ant-btn:hover {
  background-color: #e6f7ff;
}
</style>
